<template>
  <el-dialog
    class="deliver-dialog"
    :width="dialogWidth"
    append-to-body
    top="5vh"
    title="发送物流"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="handClose"
  >
    <div class="deliver-container">
      <div class="deliver-table" v-if="data.length > 0">
        <el-table :data="data">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="收件人" prop="destName"></el-table-column>
          <el-table-column label="收件地址" prop="destAddress"></el-table-column>
          <el-table-column label="发货时间" prop="createTime"></el-table-column>
          <el-table-column label="物流单号" prop="mailNo"></el-table-column>
          <el-table-column label="物流状态" prop="status">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == 0">待收货</el-tag>
              <el-tag v-if="scope.row.status == 1" type="success">已收货</el-tag>
              <el-tag v-if="scope.row.status == 2" type="danger">已拦截</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="延期提醒" prop="nextDeliveryDate"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="getDetail(scope.row)"
              >查看详情
              </el-button>
              <template v-if="scope.row.status == 0">
                <el-button
                  type="text"
                  @click="cancelOrder(scope.row)"
                  :loading="submitLoading"
                >取消物流
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-form
        class="deliver-form"
        label-width="120px"
        :model="postData"
        :rules="rules"
        ref="form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="寄件人：">{{ postData.srcName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="寄件人电话：">{{ postData.srcPhone }}</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="寄件人省市区：">{{ postData.srcProvince }}/{{ postData.srcCity }}/{{ postData.srcDistrict }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="寄件地址：">{{ postData.srcAddress }}</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收件人：" prop="destName">
              <el-input v-model="postData.destName" :disabled="showDetail" placeholder="请输入收件人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收件电话：" prop="destPhone">
              <el-input v-model="postData.destPhone" :disabled="showDetail" placeholder="请输入收件电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收件人省市区：" prop="destProvince">
              <el-cascader
                ref="cascader"
                v-if="cascaderVisible"
                placeholder="收件人省市区"
                v-model="cascaderValue"
                @change="handleChange"
                style="width: 100%"
                :options="options"
                :props="regionProps"
              >
              </el-cascader>
              <template v-if="showDetail">{{ postData.destProvince }}/{{ postData.destCity }}/{{ postData.destDistrict }}</template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收件地址：" prop="destAddress">
              <el-input v-model="postData.destAddress" :disabled="showDetail" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="寄托物名称：" prop="consignment">
              <el-input v-model="postData.consignment" :disabled="showDetail" placeholder="请输入寄托物名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="顺丰产品类型：" prop="expressType">
              <el-select v-model="postData.expressType" :disabled="showDetail" placeholder="请选择顺丰产品类型">
                <el-option label="陆运" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="参评编号：" prop="productCode">
              <el-select v-model="postData.productCode" :disabled="showDetail" placeholder="请选择">
                <el-option label="中药寄递" value="CHINESE_HERBAL"></el-option>
                <el-option label="病案寄递" value="MEDICAL_CHART"></el-option>
                <el-option label="其他" value="OTHER"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款方式：" prop="payMethod">
              <el-select v-model="postData.payMethod" :disabled="showDetail" placeholder="请选择付款方式">
                <el-option label="寄付月结" :value="1"></el-option>
                <el-option label="到付" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="保价金额：" prop="statementValue">
              <el-input-number v-model="postData.statementValue" :disabled="showDetail" placeholder="0" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重量：" prop="parcelWeighs">
              <el-input-number v-model="postData.parcelWeighs" :disabled="showDetail" placeholder="0" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="包裹数量：" prop="packagesNo">
              <el-input-number v-model="postData.packagesNo" :disabled="showDetail" placeholder="1" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="延期时间：" prop="nextDeliveryDate">
              <el-date-picker
                v-model="postData.nextDeliveryDate"
                value-format="yyyy-MM-dd"
                :disabled="showDetail"
                :clearable="false"
                :editable="false"
                :picker-options="pickerOptions"
                type="date"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col>
            <el-form-item label="备注：" prop="remark">
              <el-input v-model="postData.remark" :disabled="showDetail" type="textarea" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <template v-if="showDetail">
        <el-button @click="onBack">返回</el-button>
      </template>
      <template v-else>
        <el-button type="primary" @click="onSubmit" :loading="submitLoading">提交</el-button>
        <el-button @click="onClose">关闭</el-button>
      </template>
    </div>
  </el-dialog>
</template>

<script>
import { addOrder, queryDestInfo, queryOrder, queryLazyTree, cancelThirdOrder } from "@/api/charges/logistics";

export default {
  name: "goDeliver",
  data() {
    return {
      visible: false,
      data: [],
      postData: {
        consignment: null,
        destAddress: null,
        destCity: null,
        destDistrict: null,
        destName: null,
        destPhone: null,
        destProvince: null,
        expressType: 2,
        orderNo: null,
        packagesNo: 1,
        parcelWeighs: null,
        payMethod: 1,
        productCode: "CHINESE_HERBAL",
        remark: null,
        srcAddress: null,
        srcCity: null,
        srcDistrict: null,
        srcName: null,
        srcPhone: null,
        srcProvince: null,
        statementValue: 0,
        nextDeliveryDate: null
      },
      rules: {
        destName: [
          { required: true, message: "请输入收件人名称", trigger: "blur" },
        ],
        destAddress: [
          { required: true, message: "请输入收件详细地址", trigger: "blur" },
        ],
        destPhone: [
          { required: true, message: "请输入收件人电话", trigger: "blur" },
        ],
        consignment: [
          { required: true, message: "请输入寄托物名称", trigger: "blur" },
        ],
        expressType: [
          { required: true, message: "请选择产品类型", trigger: "blur" },
        ],
        productCode: [
          { required: true, message: "请选择参评编号", trigger: "blur" },
        ],
        payMethod: [
          { required: true, message: "请选择付款方式", trigger: "blur" },
        ],
        statementValue: [
          { required: true, message: "请输入保价", trigger: "blur" },
        ],
        parcelWeighs: [
          { required: true, message: "请输入物品重量", trigger: "blur" },
        ],
        destProvince: [
          { required: true, message: "请选择收件人省市区", trigger: "blur" },
        ]
      },
      regionProps: {
        lazy: true,
        lazyLoad(node, resolve) {
          let parent = node.value || "00";
          queryLazyTree(node.value || "00").then(res => {
            let data = [];
            let level = node.level;
            res.forEach(item => {
              data.push({
                value: item.value,
                label: item.title,
                leaf: level >= 2
              });
            });
            resolve(data);
          });
        }
      },
      pickerOptions: {
        disabledDate(d) {
          let time = new Date();
          return d.getTime() < time.getTime();
        }
      },
      options: [],
      cascaderValue: [],
      submitLoading: false,
      cascaderVisible: true,
      oldData: null,
      showDetail: false
    }
  },
  created() {
    this._initView();
  },
  computed: {
    dialogWidth() {
      return window.innerWidth * 0.6 + "px";
    }
  },
  methods: {
    open(orderNo) {
      this.postData.orderNo = orderNo;
      this._queryDestInfo();
      this._queryOrder();
      this.visible = true;
    },
    onClose(){
      this.visible=false;
            this.$parent.crud.toQuery();
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if(valid) {
          this.submitLoading = true;
          addOrder(this.postData).then(() => {
            this.visible=false;
            this.$parent.crud.toQuery();
            this._success();
          }).catch(() => {
            this.submitLoading = false;
          });
        }
      });
    },
    getDetail(row) {
      this.oldData = {
        postData: this.postData,
        cascaderValue: this.cascaderValue
      }
      this.postData = row;
      this.cascaderVisible = false;
      this.showDetail = true;
    },
    handleChange() {
      let nodes = this.$refs.cascader.getCheckedNodes()[0].pathLabels;
      this.postData.destProvince = nodes[0];
      this.postData.destCity = nodes[1];
      this.postData.destDistrict = nodes[2];

      this.postData.provinceCode = this.cascaderValue[0];
      this.postData.cityCode = this.cascaderValue[1];
      this.postData.areaCode = this.cascaderValue[2];
    },
    onBack() {
      this.postData = this.oldData.postData;
      this.showDetail = false;
      this.oldData = null;
      this.cascaderVisible = true;
      this.$nextTick(() => {
        this._setCascaderValue();
      });
    },
    handClose() {
      if(this.showDetail) {
        this.showDetail = false;
        this.oldData = null;
      }
      this._resetForm();
    },
    cancelOrder({ bspOrderNo }) {
      this.submitLoading = true;
      cancelThirdOrder(bspOrderNo).then(() => {
        this._success();
      }).catch(() => {
        this.submitLoading = false;
      });
    },
    _initView() {
      this._loadLazyTree({
        children: this.options,
        parent: "00"
      });
    },
    _queryDestInfo() {
      queryDestInfo(this.postData.orderNo).then(res => {
        this.postData.srcName = res.store.storeName;
        this.postData.srcAddress = res.store.address;
        this.postData.srcCity = res.store.city;
        this.postData.srcProvince = res.store.province;
        this.postData.srcDistrict = res.store.area;
        this.postData.srcPhone = res.store.phone;
        if(res.order) {
          this.postData.destPhone = res.order.phone;
          this.postData.destAddress = res.order.address;
          this.postData.destCity = res.order.city;
          this.postData.destDistrict = res.order.area;
          this.postData.destName = res.order.username;
          this.postData.destProvince = res.order.province;
          this.postData.provinceCode = res.order.provinceCode,
          this.postData.cityCode = res.order.cityCode,
          this.postData.areaCode = res.order.areaCode

          this._setCascaderValue();
        }
      });
    },
    _queryOrder() {
      let length = this.data.length;
      if(length > 0) this.data.splice(0, length - 1);
      queryOrder(this.postData.orderNo).then(res => {
        this.data = res;
      });
    },
    _success() {
      this.$notify({
        title: "操作成功",
        type: "success"
      });
      this.submitLoading = false;
      this._queryOrder();
      // this._resetForm();
    },
    _resetForm() {
      this.$refs.form.resetFields();
      this.cascaderVisible = [];
      this.cascaderVisible = false;
      this.$nextTick(() => {
        this.cascaderVisible = true;
      });
    },
    _loadLazyTree({ parent, children}) {
      queryLazyTree(parent).then(res => {
        res.forEach(item => {
          children.push({
            value: item.value,
            label: item.title
          });
        });
      });
    },
    _setCascaderValue() {
      let { provinceCode,cityCode,areaCode } = this.postData;
      this.cascaderValue = [ provinceCode, cityCode, areaCode ];
      let cascader = this.$refs["cascader"];
      cascader.panel.activePath=[];
      cascader.panel.loadCount=0;
      cascader.panel.lazyLoad();
    }
  }
}
</script>

<style>
.deliver-table {
  margin-bottom: 10px;
}
</style>
